/**
 * Copyright (c) 2024,  科泰集团教研团队
 * 版权所有，请勿侵权
 */
package com.ktjiaoyu.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.view.UrlBasedViewResolver;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 科泰集团教研团队
 * @version 1.0.0
 * @packageName com.ktjiaoyu.controller
 * @fileName BaseController.java
 * @createTime 2024/10/17 19:48
 * @lastModify 2024/10/17 19:48
 */
public class BaseController {
    private static final Logger LOGGER =
            LoggerFactory.getLogger(BaseController.class);
    /** 使用@InitBinder解决SpringMVC日期类型无法绑定的问题 */
//    @InitBinder
//    public void initBinder(WebDataBinder dataBinder){
//        LOGGER.info("进入BaseController的initBinder方法");
//        dataBinder.registerCustomEditor(Date.class,
//                new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
//    }

    /** 转发到任意路径 */
    public String forward(String url){
        return UrlBasedViewResolver.FORWARD_URL_PREFIX + url;
    }
    /** 重定向到任意路径 */
    public String redirect(String url){
        return UrlBasedViewResolver.REDIRECT_URL_PREFIX + url;
    }
    /** 获取request对象  */
    public HttpServletRequest request(){
        return ((ServletRequestAttributes) RequestContextHolder
                    .getRequestAttributes()).getRequest();
    }
    /** 设置数据到request作用域中  */
    public void request(String name, Object obj){
        request().setAttribute(name, obj);
    }
    /** 从request作用域中获取数据  */
    public <T> T request(String name){
        return (T)request().getAttribute(name);
    }
    /** 获取session对象 */
    public HttpSession session(){
        return request().getSession();
    }
    /** 设置数据到session作用域中  */
    public void session(String name, Object obj){
        session().setAttribute(name, obj);
    }
    /** 从session作用域中获取数据  */
    public <T> T session(String name){
        return (T)session().getAttribute(name);
    }
}
